package com.homer.android.sdk;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;

import com.homer.android.sdk.type.user.builder.BEspUser;
import com.homer.android.sdk.user.IEspUser;
import com.homer.iot.esptouch.EsptouchTask;
import com.homer.iot.esptouch.IEsptouchListener;
import com.homer.iot.esptouch.IEsptouchResult;
import com.homer.iot.esptouch.IEsptouchTask;
import com.homer.iot.esptouch.model.Device;
import com.homer.iot.esptouch.model.Slaver;
import com.homer.iot.esptouch.tcp.UartTCPUtil;
import com.homer.iot.esptouch.udp.IOTAddress;
import com.homer.iot.esptouch.udp.UdpBroadcastUtil;

public class Homer {
	private static Context context;

	private static WifiManager mWifiManager;

	private static IResult rel;
	
	private static IEsptouchTask mEsptouchTask;
	
	private static String appKey;

	// protected static IEspUser mUser = BEspUser.getBuilder().getInstance();;

	//mWaitUdpReceivingMilliseond = 15000;
	//mWaitUdpSendingMillisecond = 45000;
    //waitTotalMillisecond=mWaitUdpReceivingMilliseond+mWaitUdpSendingMillisecond
	public static void startSmartConnect(Context context, String apSsid,
			String apPassword, IResult result,int waitTotalMillisecond) {
		Homer.context = context;

		Homer.mWifiManager = (WifiManager) context
				.getSystemService(Context.WIFI_SERVICE);

		Homer.rel = result;
		String timeOut = String.valueOf(waitTotalMillisecond);

		new EsptouchAsyncTask3().execute(apSsid, getConnectionBssid(),
				apPassword, "NO", "0",timeOut);

	}

	public static void searchDevice(final ISearchResult iSearchResult) {
		final List<Device> deviceList = new ArrayList<Device>();
		Runnable r = new Runnable() {
			public void run() {
				List<IOTAddress> result = doCommandDeviceDiscoverLocal();
				for (IOTAddress iotAddress : result) {
					String deviceId = UartTCPUtil.getDeviceID(iotAddress
							.getInetAddress().getHostAddress());
					List<Slaver> slaverList = UartTCPUtil.getSlaverList(iotAddress
							.getInetAddress().getHostAddress());
					Device device = new Device(iotAddress.getInetAddress()
							.getHostAddress(), deviceId/*, slaverList*/);
					device.getSlaverList();
					deviceList.add(device);
					
					
				}
				iSearchResult.onResult(deviceList);
			}
		};

		Thread t = new Thread(r);
		t.start();

		//return deviceList;
	}
	
	public static boolean cancelSmartConnect(){
		mEsptouchTask.interrupt();
		return mEsptouchTask.isCancelled();
	}


	private static List<IOTAddress> doCommandDeviceDiscoverLocal() {
		List<IOTAddress> result = UdpBroadcastUtil.discoverIOTDevices();

		return result;
	}

	static private IEsptouchListener myListener = new IEsptouchListener() {

		@Override
		public void onEsptouchResultAdded(final IEsptouchResult result) {
			onEsptoucResultAddedPerform(result);
		}
	};

	static private void onEsptoucResultAddedPerform(final IEsptouchResult result) {

		rel.onResult(result);
	}

	private static class EsptouchAsyncTask3 extends
			AsyncTask<String, Void, List<IEsptouchResult>> {

		private IEsptouchTask mEsptouchTask;

		private final Object mLock = new Object();

		@Override
		protected void onPreExecute() {
		}

		@Override
		protected List<IEsptouchResult> doInBackground(String... params) {
			int taskResultCount = -1;
			synchronized (mLock) {
				String apSsid = params[0];
				String apBssid = params[1];
				String apPassword = params[2];
				String isSsidHiddenStr = params[3];
				String taskResultCountStr = params[4];
				String waitTotalMillisecond = params[5];
				boolean isSsidHidden = false;
				if (isSsidHiddenStr.equals("YES")) {
					isSsidHidden = true;
				}
				taskResultCount = Integer.parseInt(taskResultCountStr);
				int timeout = Integer.parseInt(waitTotalMillisecond);
				mEsptouchTask = new EsptouchTask(apSsid, apBssid, apPassword, isSsidHidden, timeout, context) ;
//				EsptouchTask(apSsid, apBssid, apPassword,
//						isSsidHidden, context,waitTotalMillisecond);
//				
				mEsptouchTask.setEsptouchListener(myListener);
			}
			List<IEsptouchResult> resultList = mEsptouchTask
					.executeForResults(taskResultCount);
			return resultList;
		}

		@Override
		protected void onPostExecute(List<IEsptouchResult> result) {

			IEsptouchResult firstResult = result.get(0);
			// 回调结果
			//rel.onResult(firstResult);
			// check whether the task is cancelled and no results received
			if (!firstResult.isCancelled()) {
				int count = 0;
				// max results to be displayed, if it is more than
				// maxDisplayCount,
				// just show the count of redundant ones
				final int maxDisplayCount = 5;
				// the task received some results including cancelled while
				// executing before receiving enough results
				if (firstResult.isSuc()) {
					StringBuilder sb = new StringBuilder();
					for (IEsptouchResult resultInList : result) {
						sb.append("Esptouch success, bssid = "
								+ resultInList.getBssid()
								+ ",InetAddress = "
								+ resultInList.getInetAddress()
										.getHostAddress() + "\n");
						count++;
						if (count >= maxDisplayCount) {
							break;
						}
					}
					if (count < result.size()) {
						sb.append("\nthere's " + (result.size() - count)
								+ " more result(s) without showing\n");
					}

				} else {

				}
			}
		}
	}

	public static String getAppKey() {
		return appKey;
	}

	public static void setAppKey(String appKey) {
		Homer.appKey = appKey;
	}

	private static String getConnectionBssid() {
		WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
		if (wifiInfo != null) {
			return wifiInfo.getBSSID();
		}

		return null;
	}
}
